{{template "admin/header.html"}}
<title>修改内容 - GPRESS</title>
<link rel="stylesheet" type="text/css" href="{{basePath}}admin/js/cherry-markdown/cherry-markdown.min.css" />
<link href="{{basePath}}admin/js/wangeditor/wangeditor5.min.css" rel="stylesheet" />
<script src="{{basePath}}admin/js/wangeditor/wangeditor5.min.js"></script>
<script type="text/javascript" src="{{basePath}}admin/js/cherry-markdown/cherry-markdown.min.js"></script>
{{template "admin/bodystart.html"}} 

{{ $category := selectList "category" "" 1 1000 "* FROM category order by sortNo desc" }}
{{ $pageTemplate := pageTemplate }} 

<div class="layui-panel" style="padding: 5px;height: 100%;">
	<form class="layui-form" id="gpress-form" action="{{basePath}}admin/{{.UrlPathParam}}/update" method="POST" style="height:100%;display: flex;flex-direction: column;">
		<div class="layui-form-item">
			<div class="layui-col-md3">
				<label class="layui-form-label">ID</label>
				<div class="layui-input-block">
					<input type="hidden" name="id" id="id" value="{{.Data.Id}}" />
					<input type="text" autocomplete="off" class="layui-input"  disabled value="{{.Data.Id}}" />
				</div>
			</div>
			<div class="layui-col-md3">
				<label class="layui-form-label">文章标题</label>
				<div class="layui-input-block">
					<input type="text" name="title" lay-verify="required" lay-reqtext="请填写文章标题" autocomplete="off"
						class="layui-input" value="{{.Data.Title}}">
				</div>
			</div>
			<div class="layui-col-md3">
				<label class="layui-form-label">摘要</label>
				<div class="layui-input-block">
					<input type="text" name="summary" autocomplete="off" class="layui-input" value="{{.Data.Summary}}">
				</div>
			</div>
			<div class="layui-col-md3">
				<label class="layui-form-label">keyword</label>
				<div class="layui-input-block">
					<input type="text" name="keyword" autocomplete="off" class="layui-input" value="{{.Data.Keyword}}">
				</div>
			</div>
		</div>

		<div class="layui-form-item">
			<div class="layui-col-md3">
				<label class="layui-form-label">导航菜单</label>
				<div class="layui-input-block">
					<select name="categoryID" id="categoryID" lay-verify="required" lay-reqtext="请选择导航菜单">
						<option value="">请选择</option>
						{{ range $index,$obj := $category.Data }}
						<option value="{{$obj.Id}}">{{$obj.Name}}</option>
						{{end}}
					</select>
				</div>
			</div>
			<div class="layui-col-md3">
				<label class="layui-form-label">页面模版</label>
				<div class="layui-input-block">
					<select name="templateID" id="templateID">
						<option value="">默认(content.html)</option>
						{{ range $index,$obj := $pageTemplate }}
						<option value="{{$obj.Id}}">{{$obj.Name}}</option>
						{{end}}
					</select>
				</div>
			</div>
			<div class="layui-col-md3">
				<label class="layui-form-label">状态</label>
				<div class="layui-input-block">
					<select name="status" id="status">
						<option value="1">公开</option>
						<option value="0">链接访问</option>
						<option value="2">私密</option>
					</select>
				</div>
			</div>
			<div class="layui-col-md3">
				<label class="layui-form-label">排序</label>
				<div class="layui-input-block">
					<input type="number" name="sortNo" lay-verify="required" lay-reqtext="请填写排序" autocomplete="off"
						class="layui-input" value="{{.Data.SortNo}}">
				</div>
			</div>
		</div>

		<div class="layui-form-item">
			<div class="layui-col-md3">
				
				<label class="layui-form-label">封面图</label>
				<div class="layui-input-block">
					<button type="button" class="layui-btn" id="button-upload-thumbnail">
						<i class="layui-icon layui-icon-upload"></i> 上传封面
					</button>
					
					<img height="38px" src="{{.Data.Thumbnail}}" id="img_thumbnail" style="padding-left: 10px;" />
					<i id="i_delete_thumbnail" class="layui-icon layui-icon-delete" style="font-size: 20px;display: none;"></i> 
				   
				</div>
			        
			</div>
			<div class="layui-col-md3">
				<label class="layui-form-label">description</label>
				<div class="layui-input-block">
					<input type="text" name="description" autocomplete="off" class="layui-input" value="{{.Data.Description}}">
				</div>
			</div>
			<div class="layui-col-md3">
				<label class="layui-form-label">作者</label>
				<div class="layui-input-block">
					<input type="text" name="author" autocomplete="off" class="layui-input" value="{{.Data.Author}}">
				</div>
			</div>
			<div class="layui-col-md3">
				<label class="layui-form-label">tag标签</label>
				<div class="layui-input-block">
					<input type="text" name="tag" autocomplete="off" class="layui-input" value="{{.Data.Tag}}">
				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">文章内容</label>
			<div class="layui-input-block">
				<input type="radio" name="contentType" value="0" title="Markdown" checked lay-filter="contentType" />
				<input type="radio" name="contentType" value="1" title="富文本" lay-filter="contentType" />
				<button type="submit" class="layui-btn layui-bg-blue" lay-submit
					lay-filter="gpress-form-ajax-update">提交修改</button>
			</div>
		</div>
		<div class="layui-form-item" style="flex:1">
			<div id="markdown-container" style="height: 100%;"></div>
            <div id="editor-wrapper" style="display: none;height: 100%;">
			<div style="display: flex;height: 100%;overflow: auto;flex-direction: column;">
				<div id="toolbar-container"><!-- 工具栏 --></div>
				<div id="editor-container" style="flex:1"><!-- 编辑器 --></div>
			</div>
		    </div>
		</div>


	</form>
</div>
{{template "admin/bodyend.html"}}

<script>
	layui.use(function () {
		var form = layui.form;
		var layer = layui.layer;
		var upload = layui.upload;
		var $ = layui.jquery;
   
		//选中导航菜单
		$("#categoryID option[value='{{.Data.CategoryID}}']").attr("selected", true);
		//选中模板
		$("#templateID option[value='{{.Data.TemplateID}}']").attr("selected", true);
		//选中状态
		$("#status option[value='{{.Data.Status}}']").attr("selected", true);

		// 缩略图
		var thumbnail = "{{.Data.Thumbnail}}";
		var content = "";
		if("{{.Data.Markdown}}"==""){//不是markdown格式
			content="{{.Data.Content}}";
			$("input:radio[name='contentType'][value='1']").attr("checked",true);  
			$('#markdown-container').hide()
			$('#editor-wrapper').show()
		}
		// 渲染全部表单
		form.render(); 

		// 上传文件
		upload.render({
			elem: '#button-upload-thumbnail',
			url: '{{basePath}}admin/upload', // 此处配置你自己的上传接口即可
			size: 5 * 1024, // 限制文件大小,单位 KB
			done: function (res) {
				if (res.statusCode == 1) {
					thumbnail = res.data;
					$("#img_thumbnail").attr("src", thumbnail);
					$("#i_delete_thumbnail").show();
				}
				console.log(res);
			}
		});

		$("#i_delete_thumbnail").click(function () {
			thumbnail="";
			$("#img_thumbnail").attr("src", "");
			$("#i_delete_thumbnail").hide();
		})

		$("#img_thumbnail").click(function () {
			layer.photos({
				photos: {
					"title": "封面图",
					"start": 0,
					"data": [{
					  "src": thumbnail,
					}]
				},
				//toolbar: false,
				footer: false // 是否显示底部栏 --- 2.8.16+
			});
		});

		// cherry markdown 编辑器
		var cherry = new Cherry({
			id: 'markdown-container',
			value: '{{.Data.Markdown}}',
			fileUpload: function (file, callback) {
				var formdata = new FormData(); // FormData对象,来发送二进制文件.
				formdata.append('file', file); // 将文件追加到 formdata对象中
				$.ajax({
					type: 'post',
					url: '{{basePath}}admin/upload',
					data: formdata,
					processData: false,
					contentType: false,
					success(res) {
						callback(res.data);
					},
					error(err) { },
				});
			},
			toolbars: {
				// 定义顶部工具栏
				toolbar: [
					'undo', 'redo', '|',
					// 把字体样式类按钮都放在加粗按钮下面
					{ bold: ['bold', 'italic', 'underline', 'strikethrough', 'sub', 'sup', 'ruby'] },
					'color', 'size', '|', 'header', 'list', 'panel', '|',
					// 把插入类按钮都放在插入按钮下面
					{ insert: ['image', 'audio', 'video', 'link', 'hr', 'br', 'code', 'formula', 'toc', 'table', 'drawIo'] },
					'graph'
				],
				// 定义侧边栏,默认为空
				//sidebar: ['theme', 'mobilePreview', 'copy'],
				// 定义顶部右侧工具栏,默认为空
				toolbarRight: ['fullScreen'],
				// 定义选中文字时弹出的“悬浮工具栏”,默认为 ['bold', 'italic', 'underline', 'strikethrough', 'sub', 'sup', 'quote', '|', 'size', 'color']
				bubble: ['bold', 'italic', 'underline', 'strikethrough', 'sub', 'sup', 'ruby', '|', 'color', 'size',],
				// 定义光标出现在行首位置时出现的"提示工具栏",默认为 ['h1', 'h2', 'h3', '|', 'checklist', 'quote', 'table', 'code']
				//float: ['table', 'code', 'graph'],
			},
		});

		// 富文本编辑器
		const { createEditor, createToolbar } = window.wangEditor
		
		const editorConfig = {
			placeholder: '请输入内容...',
			MENU_CONF: {},
			onChange(editor) {
				content = editor.getHtml()
				// 也可以同步到 <textarea>
			},
		}
		var editorUploadConfig = {
			server: '{{basePath}}admin/upload',
			fieldName: 'file',
			// 单个文件的最大体积限制,默认为 10M
			maxFileSize: 100 * 1024 * 1024, // 100M
			customInsert(res, insertFn) {
				// 自定义返回数据结构.不用按照wangeditor默认规定的服务器返回的数据结构
				insertFn(res.data)
			},
			onSuccess(file, res) {
				console.log(res, '--上传成功---')
			},
			onFailed(file, res) {
				layer.msg("上传失败!");
			},
			onError(file, err, res) {
				console.log('--上传错误---')
			},
		};
		editorConfig.MENU_CONF['uploadImage'] = editorUploadConfig;
		editorConfig.MENU_CONF['uploadVideo'] = editorUploadConfig;
		const editor = createEditor({
			selector: '#editor-container',
			html: content,
			config: editorConfig,
			mode: 'default', // or 'simple'
		})
		const toolbar = createToolbar({
			editor,
			selector: '#toolbar-container',
			//config: {},
			config: { excludeKeys: ['todo','divider','redo'] },
			mode: 'default', // or 'simple'
		})

		// 切换 富文本 和 Markdown
		form.on('radio(contentType)', function (data) {
			var elem = data.elem; // 获得 radio 原始 DOM 对象
			// var checked = elem.checked; // 获得 radio 选中状态
			var current = elem.value; // 获得 radio 值
			if (current == 0) {
				$('#markdown-container').show()
				$('#editor-wrapper').hide()
			} else {
				$('#markdown-container').hide()
				$('#editor-wrapper').show()
			}
		})


		// 提交事件
		form.on('submit(gpress-form-ajax-update)', function (data) {
			var field = data.field; // 获取表单字段值
			field.sortNo = field.sortNo - 0;
			field.status = field.status - 0;
			field.thumbnail = thumbnail;
			field.code = "";
			field.categoryName = $("#categoryID").find("option:selected").text();
			//选中的文章类型
			let contentType=$("input:radio[name='contentType']:checked").val(); 
			if(contentType=="1"){//富文本
				field.content = content;
				field.markdown= "";
			}else{
				field.content="";
				field.markdown = cherry.getMarkdown();
			}

			//表单对象
			const form = document.getElementById('gpress-form');
			$.ajax({
				url: form.action,
				type: form.method,
				contentType: "application/json;charset=utf-8",
				dataType: "json",
				data: JSON.stringify(field),
				error: function () {
					layer.msg("修改错误,请重试!");
				},
				success: function (result) {
					if (result.statusCode == 1) {
						layer.confirm('修改成功,是否继续修改?', {
							icon: 3,
							title: "确认",
							btn: ['返回列表', '继续修改'] //按钮
						}, function () {
							window.location.href = '{{basePath}}admin/{{.UrlPathParam}}/list';
						});
					} else {
						layer.msg("修改失败!");
					}
				}
			});
			return false; // 阻止默认 form 跳转
		});
	});
</script>

